let path = require('path');
let glob = require('glob');
let FileManagerPlugin = require('filemanager-webpack-plugin');
let BuildInfoPlugin = require('./build/build-info-plugin')


function getPages(globPath) {
  let pages = {};
  glob.sync(globPath).forEach(function (entry) {
    let basename = path.basename(entry, path.extname(entry));
    let [pagesDir, name, filename] = entry.split('/').splice(-3);
    pages[basename] = {
      entry: `src/${pagesDir}/${name}/${name}.js`,
      template: `src/${pagesDir}/${name}/${filename}`,
      title: name,
      filename: filename
    };
  });
  return pages;
}

let pages = getPages('./src/pages/**?/*.html');
let assetsRoot = path.resolve(__dirname, './dist')
const cdn = process.env.NODE_ENV === 'production'
const publicCdnPath = cdn && process.env.VUE_APP_PUBLIC_CDN_PATH

let webpackPlugins = [];
if (process.env.NODE_ENV === "production") {
  webpackPlugins = [
    new BuildInfoPlugin({assetsRoot: assetsRoot}),
    new FileManagerPlugin({
      onEnd: {
        delete: ['./frontend-h5-common_'+ process.env.VUE_APP_MODE +'.zip'],
        archive: [
          {source: './dist/', destination: './frontend-h5-common_'+ process.env.VUE_APP_MODE+'.zip'},
        ]
      }
    })
  ]
}


module.exports = {
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: true,
    // 开启 CSS source maps?
    sourceMap: false,
    // 启用 CSS modules for all css / pre-processor files.
    modules: false,
    loaderOptions: {
      stylus: {
        'resolve url': true,
        'import': []
      }
    }
  },
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.join(__dirname, 'src')
      }
    },
    externals: {
      vue: "Vue"
    },
    plugins: webpackPlugins
  },
  productionSourceMap: false,
  pages: pages,
  outputDir: 'dist',
  assetsDir: 'static',
  devServer: {
    port: 8081,
    index: 'wxlogin.html', //默认启动serve 打开page1页面,
    // proxy: {
    //   '/api': {
    //     target: '',
    //     logLevel: "debug",
    //     ws: true,
    //     changeOrigin: true,
    //     onProxyReq: function (proxyReq) {
    //       proxyReq.setHeader('Cookie', 'X-MP-TOKEN=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ3eGYzZDQ5MmNhOGIxZWYxM2MiLCJpZCI6Ijk5NCIsInVzZXJfaWQiOiJvTFdfRjBnLTgwZlgzN3BiREJpWGZjZGs1ZVNjIiwiYnVzaW5lc3NfaWQiOjEsInZlcnNpb24iOiIxLjAuMiIsIm1ldGhvZCI6Miwic2NvcGUiOiJtcF9jdXN0b21lciIsImV4cCI6MTU5MTE1NjA5NX0.8kyKidkuIdS4nqHCtcKoCSqRuVyfM0vgXSL0cUdVGvg');
    //     }
    //   }
    // }
  },
  publicPath: cdn ? publicCdnPath : "/h5/common/",
};
